package com.example.demo.controller;

import com.alibaba.fastjson2.JSONObject;
import com.example.demo.exception.BusyException;
import com.example.demo.mapper.*;
import com.example.demo.entity.*;
import com.example.demo.entity.Dto.StuExDto;
import com.example.demo.util.DownloadUtil;
import com.example.demo.util.OutUtil;
import com.example.demo.util.POIUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/exam")
@CrossOrigin
public class ExaminController {
    @Autowired
    private StuExternalMapper sem;
    @Autowired
    private StudentMapper sm;
    @Autowired
    private CollegesMapper cm;
    @Autowired
    private TeacherMapper tm;
    @Autowired
    private ScoreMapper scm;
    @Autowired
    private UserInfoMapper uim;

    @RequestMapping("/needexamin")
    public void needExamin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String graduationGredit = request.getParameter("graduationGredit");
        String englishTestFour = request.getParameter("englishTestFour");
        String computerLevel = request.getParameter("computerLevel");
        String totalCredit = request.getParameter("totalCredit");
        Colleges colleges = new Colleges();
        if (graduationGredit != null && !"".equals(graduationGredit)) {
            colleges.setGraduationGredit(Float.valueOf(graduationGredit));
        }
        if (englishTestFour != null && !"".equals(englishTestFour)) {
            colleges.setEnglishTestFour(Integer.valueOf(englishTestFour));
        }
        if (computerLevel != null && !"".equals(computerLevel)) {
            colleges.setComputerLevel(computerLevel);
        }
        if (totalCredit != null && !"".equals(totalCredit)) {
            colleges.setTotalCredit(Integer.valueOf(totalCredit));
        }
        List<StuExternal> stuExternals = sem.selectByNeed(colleges);
        List<StuExternal> stuExternals1 = sem.selectByInNeed(colleges);
        Map<String, List<StuExternal>> map = new HashMap<>();
        map.put("pass", stuExternals);
        map.put("inpass", stuExternals1);
        response.getWriter().write(com.alibaba.fastjson2.JSONObject.toJSONString(Message.success(map)));
    }

    @RequestMapping("/atain")
    public void atain(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Student> alllStu = sm.findAlllStu();
        List<StuExternal> list = new ArrayList<>();
        List<StuExternal> list1 = new ArrayList<>();
        List<StuExternal> list2 = new ArrayList<>();
        for (Student s : alllStu) {
            List<Score> scoreByOne = scm.findScoreByOne(s.getId());
            if (scoreByOne.size() != 0) {
                UserInfo userInfo = uim.selectByName(s.getName());
                if (userInfo == null) userInfo = new UserInfo(s.getName(), "汉族", "1010101@qq.com", 24, 1);
                if ("汉族".equals(userInfo.getNation())) {
                    Colleges colleges = cm.selectByCollegeAndVersion(s.getCollege(), s.getGrade().split("级")[0]);
                    StuExternal stuExternal = sem.selectByIdTerm(s.getId(), "end");
                    if (stuExternal != null) {
                        if (stuExternal.getGredit() >= colleges.getGraduationGredit() && stuExternal.getEnglishTestFour() > colleges.getEnglishTestFour()
                                && stuExternal.getCredit() >= colleges.getTotalCredit() && stuExternal.getComputerLevel().compareTo(colleges.getComputerLevel()) >= 0) {
                            list.add(stuExternal);
                        } else if (stuExternal.getGredit() >= colleges.getGraduationGredit() && stuExternal.getCredit() >= colleges.getTotalCredit()) {
                            list1.add(stuExternal);
                        } else list2.add(stuExternal);
                    }
                } else {
                    Colleges colleges = cm.selectByCollegeAndVersion(s.getCollege(), s.getGrade().split("级")[0]);
                    StuExternal stuExternal = sem.selectByIdTerm(s.getId(), "end");
                    if (stuExternal != null) {
                        if (stuExternal.getGredit() >= colleges.getGraduationGredit() && stuExternal.getEnglishTestFour() > (colleges.getEnglishTestFour() - 20)
                                && stuExternal.getCredit() >= colleges.getTotalCredit() && stuExternal.getComputerLevel().compareTo(colleges.getComputerLevel()) >= 0) {
                            list.add(stuExternal);
                        } else if (stuExternal.getGredit() >= colleges.getGraduationGredit() && stuExternal.getCredit() >= colleges.getTotalCredit()) {
                            list1.add(stuExternal);
                        } else list2.add(stuExternal);
                    }
                }
            }
        }
        Map<String, List<StuExternal>> map = new HashMap<>();
        map.put("allpass", list);
        map.put("gpass", list1);
        map.put("inpass", list2);
        response.getWriter().write(JSONObject.toJSONString(Message.success(map)));
    }

    @RequestMapping("/atainT")
    public void atainT(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Teacher t = tm.findTeaByName(request.getParameter("user"));
        List<Student> alllStu = sm.findStuByCollegeAndGrade(t.getCollege(), t.getGrade());
        List<StuExternal> list = new ArrayList<>();
        List<StuExternal> list1 = new ArrayList<>();
        List<StuExternal> list2 = new ArrayList<>();
        for (Student s : alllStu) {
            Colleges colleges = cm.selectByCollegeAndVersion(s.getCollege(), s.getGrade().split("级")[0]);
            StuExternal stuExternal = sem.selectByIdTerm(s.getId(), "end");
            if (stuExternal.getGredit() >= colleges.getGraduationGredit() && stuExternal.getEnglishTestFour() > colleges.getEnglishTestFour()
                    && stuExternal.getCredit() >= colleges.getTotalCredit() && stuExternal.getComputerLevel().compareTo(colleges.getComputerLevel()) >= 0) {
                list.add(stuExternal);
            } else if (stuExternal.getGredit() >= colleges.getGraduationGredit() && stuExternal.getCredit() >= colleges.getTotalCredit()) {
                list1.add(stuExternal);
            } else list2.add(stuExternal);
        }
        Map<String, List<StuExternal>> map = new HashMap<>();
        map.put("allpass", list);
        map.put("gpass", list1);
        map.put("inpass", list2);
        response.getWriter().write(JSONObject.toJSONString(Message.success(map)));
    }

    @RequestMapping("/atainstu")
    public void atainStu(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Student student = sm.selectByName(request.getParameter("user"));
        List<StuExternal> list = new ArrayList<>();
        List<StuExternal> list1 = new ArrayList<>();
        List<StuExternal> list2 = new ArrayList<>();
        Colleges colleges = cm.selectByCollegeAndVersion(student.getCollege(), student.getGrade().split("级")[0]);
        StuExternal stuExternal = sem.selectByIdTerm(student.getId(), "end");
        UserInfo userInfo = uim.selectByName(student.getName());
        Map<String, List<StuExternal>> map = new HashMap<>();
        if ("汉族".equals(userInfo.getNation())) {
            if (stuExternal.getGredit() >= colleges.getGraduationGredit() && stuExternal.getEnglishTestFour() > colleges.getEnglishTestFour()
                    && stuExternal.getCredit() >= colleges.getTotalCredit() && stuExternal.getComputerLevel().compareTo(colleges.getComputerLevel()) >= 0) {
                list.add(stuExternal);
            } else if (stuExternal.getGredit() >= colleges.getGraduationGredit() && stuExternal.getCredit() >= colleges.getTotalCredit()) {
                list1.add(stuExternal);
            } else list2.add(stuExternal);
            map.put("allpass", list);
            map.put("gpass", list1);
            map.put("inpass", list2);
        } else {
            if (stuExternal.getGredit() >= colleges.getGraduationGredit() && stuExternal.getEnglishTestFour() > (colleges.getEnglishTestFour() - 20)
                    && stuExternal.getCredit() >= colleges.getTotalCredit() && stuExternal.getComputerLevel().compareTo(colleges.getComputerLevel()) >= 0) {
                list.add(stuExternal);
            } else if (stuExternal.getGredit() >= colleges.getGraduationGredit() && stuExternal.getCredit() >= colleges.getTotalCredit()) {
                list1.add(stuExternal);
            } else list2.add(stuExternal);
            map.put("allpass", list);
            map.put("gpass", list1);
            map.put("inpass", list2);
        }
        response.getWriter().write(JSONObject.toJSONString(Message.success(map)));
    }

    @PostMapping("/outport")
    public void outport(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List data = JSONObject.parseObject(request.getParameter("data"), List.class);
        List<Exam> exams = new ArrayList<>();
        Map<Integer, List<StuExternal>> map = new HashMap<>();
        for (int i = 0; i < data.size(); i++) {
            Exam exam = JSONObject.parseObject(data.get(i).toString(), Exam.class);
            map.put(exam.getId(), sem.findByIdGroupByTerm(exam.getId()));
            if (map.get(exam.getId()).size() != 8) {
                List list = map.get(exam.getId());
                for (int j = map.get(exam.getId()).size(); j < 8; j++) {
                    list.add(null);
                }
                map.put(exam.getId(), list);
            }
            exam.setMajor(sm.selectStuById(exam.getId()).getMajor());
            exams.add(exam);
        }
        request.getSession().setAttribute("data", exams);
        request.getSession().setAttribute("map", map);
        response.getWriter().write(JSONObject.toJSONString(Message.success("success")));
    }

    @RequestMapping("/handle")
    public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Exam> exams = (List<Exam>) request.getSession().getAttribute("data");
        Map<Integer, List<StuExternal>> map = (Map<Integer, List<StuExternal>>) request.getSession().getAttribute("map");
        OutUtil outUtil = new OutUtil();
        outUtil.exportExcel(response, exams, map);
    }

    @RequestMapping("/selectAll")
    public String selectAll() {
        List<Student> alllStu = sm.findAlllStu();
        Map<String, Integer> map = new HashMap<>(5);
        List<StuExDto> result = new ArrayList<>(alllStu.size());
        map.put("无", 0);
        map.put("一级", 1);
        map.put("二级", 2);
        map.put("三级", 3);
        map.put("四级", 4);
        int maxComputer = 0;
        String maxLevel = "无";
        for (Student student : alllStu) {
            List<StuExternal> stuExternals = sem.selectById(student.getId());
            int englishFour = sem.selectMaxFour(student.getId());
            for (StuExternal stuExternal : stuExternals) {
                if (map.get(stuExternal.getComputerLevel()) > maxComputer) {
                    maxComputer = map.get(stuExternal.getComputerLevel());
                    maxLevel = stuExternal.getComputerLevel();
                }
            }
            result.add(new StuExDto(student.getId(), student.getName(), student.getCollege(), student.getMajor(), student.getGrade(),englishFour, maxLevel));
            maxComputer = 0;
            maxLevel = "无";
        }
        return JSONObject.toJSONString(Message.success(result));
    }


    @RequestMapping("/update")
    public String update(HttpServletRequest request) {
        String id = request.getParameter("id");
        String englishTestFour = request.getParameter("englishTestFour");
        String computerLevel = request.getParameter("computerLevel");
        if (id == null || "".equals(id) || englishTestFour == null || "".equals(englishTestFour) || computerLevel == null || "".equals(computerLevel))
            return JSONObject.toJSONString(Message.failure("date is can not null"));
        int update = sem.update(Integer.valueOf(id), Integer.valueOf(englishTestFour), computerLevel);
        if(update>0) return JSONObject.toJSONString(Message.success("success update"));
        else return JSONObject.toJSONString(Message.failure("update failure"));
    }

    @RequestMapping("/import")
    public String importFourScore(MultipartFile file,@RequestParam("user") String user){
        List<StuExternal> stuFourDtos = POIUtil.excelFourScore(file);
        for(StuExternal stuExternal:stuFourDtos){
            int i = sem.updateMu(stuExternal);
            if(i<=0) {
                throw new BusyException("发生业务异常");
            }
        }
       return JSONObject.toJSONString(Message.success("success upload"));
    }

    @RequestMapping("/download")
    public void download(HttpServletResponse response){
        DownloadUtil util=new DownloadUtil();
        util.exportExce2(response);
    }
}
